package com.xzy.controller;

import com.xzy.domain.Dto;
import com.xzy.domain.User;
import com.xzy.service.TokenService;
import com.xzy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;
    /**
     *成 功登录，返回token
     * token生成为设备+创建时间+过期时间两天
     */
    @PostMapping("/login")
    public Dto login(User user, HttpServletRequest request) {
        Dto dto = new Dto();
        User getUser = this.userService.login(user);

        if (getUser != null) { //成功
            String userAgentStr = request.getHeader("user-agent");
            //生成token
            String token = this.tokenService.generateToken(userAgentStr, getUser.getUsername());

            //保存token
            this.tokenService.save(token, user);
            //更新登录状态
            dto.setToken(token);
            dto.setIsLogin("true");
            dto.setTokenCreatedDate(System.currentTimeMillis());
            dto.setTokenExpiryDate(System.currentTimeMillis() + 1);
        } else { //失败
            dto.setIsLogin("false");

        }
        return dto;
    }

    @PostMapping("/getxzy1")
    public String getXzy1(User user){
        String getToken=tokenService.get(user.getUsername()+user.getId());
        System.out.println(user.getUsername()+user.getId());
        System.out.println(getToken);
        return getToken;
    }
}